package com.frame.framework.web.service.imp;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.utils.security.ShiroUtils;
import com.frame.framework.web.domain.BaseEntity;
import com.frame.framework.web.error.exception.RootAnomalyException;
import com.frame.framework.web.repository.BaseRepository;
import com.frame.framework.web.service.BaseService;



/**
 * @className ：AbstractBaseService
 * @describe ：基类 注入泛型repository ， 实现BaseService 接口的方法 CRUD
 */
public abstract class AbstractBaseService<T extends BaseEntity> implements BaseService<T>{
	
	@Autowired
	protected BaseRepository<T, Long> proxyRepository;

	@Override
	@Transactional(readOnly=true)
	public List<T> findAllList() throws RootAnomalyException {
		return proxyRepository.findAll();
	}

	@Override
	@Transactional
	public void add(T t) throws RootAnomalyException {
		t.setCreateBy(ShiroUtils.getLoginName());
		t.setCreateTime(new Date());
		t.setRemoveStatus(RemoveEnum.NOT_REMOVE.getCode());
		proxyRepository.save(t);
	}

	@Override
	@Transactional
	public void modify(T t) throws RootAnomalyException {
		t.setUpdateBy(ShiroUtils.getLoginName());
		t.setUpdateTime(new Date());
		proxyRepository.save(t);
	}

	@Override
	@Transactional(noRollbackFor=Exception.class)
	public void remove(Long id) throws RootAnomalyException {
		Optional<T> userOp = proxyRepository.findById(id);
		if(userOp.isPresent()) {
			T t = userOp.get();
			t.setUpdateBy(ShiroUtils.getLoginName());
			t.setRemoveStatus(RemoveEnum.REMOVE.getCode());
			t.setUpdateTime(new Date());
			proxyRepository.save(t);
		}
	}

	@Override
	@Transactional
	public void delete(Long id) throws RootAnomalyException {
		proxyRepository.deleteById(id);
	}

	@Override
	@Transactional(readOnly=true)
	public T findById(Long id) throws RootAnomalyException {
		Optional<T> userOp = proxyRepository.findById(id);
		if(userOp.isPresent()) {
			return userOp.get();
		}
		return null;
	}

	@Override
	@Transactional(readOnly=true)
	public List<T> findAllByRs(Integer status) {
		return proxyRepository.findAll((root,query,cb) -> {
			return cb.equal(root.get("removeStatus"), status);
		});
	}

}
